<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>预约进程/历史</el-breadcrumb-item>
      <el-breadcrumb-item>查看历史会议</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert show-icon :closable="false" title="注意：只有通过审批的会议才会加入到历史会议中！" type="warning"></el-alert>

            <!-- tab标签页 -->
            <el-tabs v-model="activeName">
                <el-tab-pane label="已进行的会议" name="done">
                <el-table :data="DoneList" border stripe
                   :header-cell-style="{'text-align':'center'}"
                   :cell-style="{'text-align':'center'}">
                <el-table-column label="会议室" prop="meetingRoom"></el-table-column>
                <el-table-column label="会议主题" prop="applyTheme"></el-table-column>
                <el-table-column label="开会日期">
                    <template slot-scope="scope">
                        <div>
                            {{ $moment(scope.row.applyDate).subtract(1, 'months').format('YYYY/MM/DD') }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="开会时间">
                    <template slot-scope="scope">
                        <!-- <div v-if="scope.row.applyTimestate == 1">9:30-11:30</div>
                        <div v-if="scope.row.applyTimestate == 2">11:30-13:30</div>
                        <div v-if="scope.row.applyTimestate == 3">15:30-17:30</div>
                        <div v-if="scope.row.applyTimestate == 4">17:30-19:30</div>
                        <div v-if="scope.row.applyTimestate == 5">19:30-20:30</div> -->
                        <div >{{$moment(scope.row.applyStart).format('HH:mm')}}-{{$moment(scope.row.applyEnd).format('HH:mm')}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="申请日期">
                    <template slot-scope="scope">
                        <div>
                            {{ $moment(scope.row.applyTime).subtract(1, 'months').format('YYYY/MM/DD') }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="申请状态">
                    <template slot-scope="scope">
                        <div v-if="scope.row.applyState == 1">已查看</div>
                        <div v-if="scope.row.applyState == 2">未通过</div>
                        <div v-if="scope.row.applyState == 3">已通过</div>
                        <div v-if="scope.row.applyState == 0">未查看</div>
                    </template>
                </el-table-column >
				        <el-table-column label="操作" width="210">
						         <template slot-scope="scope" v-if='scope.row.applyState==3'>
                        <el-upload v-if="!judgeFileExist(scope.row.fileIsExist)"
                             ref="upload"
                             class="inline-block"
                             :show-file-list=false
                             :action="filesUploadUrl"
                             :data="{apply_id:scope.row.applyId}"
                             multiple
                             :limit="20"
                             :headers="requestHeader"
                             :with-credentials="true"
                             :on-success="UploadSuccess">
                           <el-button type="text" icon="el-icon-plus">上传文档</el-button>
                        </el-upload>

                        <el-upload v-if="judgeFileExist(scope.row.fileIsExist)"
                             ref="upload"
                             class="inline-block"
                             :show-file-list=false
                             :action="filesUploadUrl"
                             :data="{apply_id:scope.row.applyId}"
                             multiple
                             :limit="20"
                             :headers="requestHeader"
                             :with-credentials="true"
                             :on-success="UploadSuccess">
                        <el-button style="color:#008B8B" type="text" icon="el-icon-plus">继续上传</el-button>
                        </el-upload>
                        <el-button
                          type="text"
                          icon="el-icon-edit"
                          style="position:relative;left:10px;"
                         @click="addEditor(scope.row.applyId)">在线编辑</el-button>
                        <el-button
                          type="text"
                          icon="el-icon-view"
                         @click="getMeetingFilesList(scope.row.applyId)">查看文档</el-button>
                        <el-button
                          type="text"
                          icon="el-icon-view"
                         @click="getSignNameList(scope.row.applyId)">签到名单</el-button>


						        </template>
				        </el-table-column>
                </el-table>
                  <!-- Table -->
                  <el-dialog title="查看会议文档" :visible.sync="onedialogTableVisible" width="42%">
                    <el-table :data="meetingFilesList" max-height="250" stripe
                        :header-cell-style="{'text-align':'center'}"
                        :cell-style="{'text-align':'center'}">
                      <el-table-column label="序号" type="index" align="center" width="100" ></el-table-column>
                      <el-table-column property="fileName" label="会议文档" align="center" ></el-table-column>
                      <el-table-column label="操作"  align="center" width="180">
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            type="primary"
                            icon="el-icon-edit"
                            plain
                            @click="fileEdit(scope.row.fileName,scope.row.meetingId,scope.row.applyId)"></el-button>
                          <el-button
                            size="mini"
                            type="primary"
                            icon="el-icon-download"
                            plain
                            @click="fileDownLoad(scope.row.fileName,scope.row.meetingId)"></el-button>
                          <el-button
                            size="mini"
                            type="danger"
                            icon="el-icon-delete"
                            plain
                            @click="fileDelete(scope.row.fileName,scope.row.meetingId)"></el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-dialog>


                    <el-dialog title="在线编辑" :visible.sync="threedialogVisible" width="50%">
                           <el-form :model="form" label-width="120px">
                           <el-form-item label="文件名">
                              <el-input v-model="formTitle" style="width: 40%"></el-input>
                           </el-form-item>

                            <div id="div1"></div>
                           </el-form>
                           <template #footer>
                             <span class="dialog-footer">
                               <el-button @click="threedialogVisible = false">取 消</el-button>
                               <el-button type="primary" @click="save()">确 定</el-button>
                             </span>
                           </template>
                    </el-dialog>


                  <!-- Table -->
                  <el-dialog title="查看签到名单" :visible.sync="twodialogTableVisible" >
                    <el-table :data="signNameList" max-height="250" stripe
                      :header-cell-style="{'text-align':'center'}"
                      :cell-style="{'text-align':'center'}">
                      <el-table-column label="序号" type="index" align="center" width="100" ></el-table-column>
                      <el-table-column property="staffName" label="签到人" align="center" ></el-table-column>
                      <el-table-column property="signTime" label="签到时间" align="center" >
                         <template slot-scope="scope">
                           {{ $moment(scope.row.signTime).subtract(1, 'months').format('YYYY/MM/DD HH:mm:ss') }}
                         </template>
                      </el-table-column>
                      <el-table-column property="signIp" label="签到IP地址" align="center" ></el-table-column>
                      <el-table-column property="signBrowser" label="签到设备" align="center" ></el-table-column>
                    </el-table>
                    <div class="outButton">
                      <el-button size="small" type="success" icon="el-icon-download" @click="exportToExcel">导出数据</el-button>
                    </div>
                  </el-dialog>

                  <!-- Table -->

                    <!-- 分页区域 -->
                    <el-pagination
                    @size-change="handleSizeChangeDone"
                    @current-change="handleCurrentChangeDone"
                    :current-page="queryDone.currentPage"
                    :page-sizes="[2, 4, 8, 10]"
                    :page-size="queryDone.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="doneTotal">
                    </el-pagination>
                </el-tab-pane>
                <el-tab-pane label="未进行的会议" name="notdone">
                    <el-table :data="NotDoneList" border stripe
                       :header-cell-style="{'text-align':'center'}"
                       :cell-style="{'text-align':'center'}">
                        <el-table-column type="index"></el-table-column>
                <el-table-column label="会议室" prop="meetingRoom"></el-table-column>
                <el-table-column label="会议主题" prop="applyTheme"></el-table-column>
                <el-table-column label="开会日期">
                    <template slot-scope="scope">
                        <div>
                            {{ $moment(scope.row.applyDate).subtract(1, 'months').format('YYYY/MM/DD') }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="开会时间">
                    <template slot-scope="scope">
                        <!-- <div v-if="scope.row.applyTimestate == 1">9:30-11:30</div>
                        <div v-if="scope.row.applyTimestate == 2">11:30-13:30</div>
                        <div v-if="scope.row.applyTimestate == 3">15:30-17:30</div>
                        <div v-if="scope.row.applyTimestate == 4">17:30-19:30</div>
                        <div v-if="scope.row.applyTimestate == 5">19:30-20:30</div> -->
                        <div >{{$moment(scope.row.applyStart).format('HH:mm')}}-{{$moment(scope.row.applyEnd).format('HH:mm')}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="申请日期">
                    <template slot-scope="scope">
                        <div>
                            {{ $moment(scope.row.applyTime).subtract(1, 'months').format('YYYY/MM/DD')}}
                        </div>
                    </template>
                </el-table-column>

				<el-table-column label="操作" width="180" align="center">
				    <template slot-scope="scope" v-if='scope.row.applyState==3'>
						<el-button
						    type="text"
						    icon="el-icon-plus"
						    @click="handleAdd(scope.row.applyId)"
						>添加参会人员</el-button>
				        <el-button
				            type="text"
				            icon="el-icon-edit"
				            @click="handleSign(scope.row.applyId)"
				        >签到</el-button>
				    </template>
				</el-table-column>
                    </el-table>

          <!-- 分页区域 -->
          <el-pagination
            @size-change="handleSizeChangeNotDone"
            @current-change="handleCurrentChangeNotDone"
            :current-page="queryNotDone.currentPage"
            :page-sizes="[2, 4, 8, 10]"
            :page-size="queryNotDone.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="notDoneTotal">
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      title="提示"
      :visible.sync="centerDialogVisible"
      center>
      <div style="display: flex;justify-content: center;align-items: center;border:1px solid #000;">
        <img :src="qrCodeImg" />
      </div>
      <span slot="footer" class="dialog-footer">
		    <el-button @click="centerDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
		  </span>
    </el-dialog>
    <el-dialog
      title="添加参会人员"
      :visible.sync="addDialogVisible"
      center>
      <div style="display: flex;justify-content: center;align-items: center;">
        <el-col :span="11" :xs="20">
          <el-card>
            <el-select v-model="value" @change="selectDepartment(value)" placeholder="请选择" style="display: flex;justify-content: center;align-items: center;" size="small" >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-table :data="departmentPersonnelList" border stripe>
              <el-table-column label="员工编号" prop="staffId"></el-table-column>
              <el-table-column label="员工姓名" prop="staffName"></el-table-column>
              <el-table-column label="添加">
                <template slot-scope="scope">
                  <!-- 添加按钮 -->
                  <el-tooltip class="item" effect="dark" content="添加参会人员" placement="top" :enterable="false">
                    <el-button
                      type="text"
                      icon="el-icon-plus"
                      @click="addParticipate(scope.row)"
                    ></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="2" :xs="4">
          <span style="font-size: 40px;" >=></span>
        </el-col>
        <el-col :span="11" :xs="20">
          <el-card>
            <el-table :data="participateList" border stripe cell-style="{textAlign:'center'}">
              <el-table-column label="员工编号" prop="staffId"></el-table-column>
              <el-table-column label="员工姓名" prop="staffName"></el-table-column>
              <el-table-column label="删除">
                <template slot-scope="scope">
                  <!-- 刪除按钮 -->
                  <el-tooltip class="item" effect="dark" content="删除参会人员" placement="top" :enterable="false">
                    <el-button
                      type="text"
                      icon="el-icon-minus"
                      @click="removeParticipate(scope.$index)"
                    ></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </div>
      <span slot="footer" class="dialog-footer">
		    <el-button @click="addDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="submitParticcipate()">提交新名单</el-button>
		  </span>
    </el-dialog>
  </div>
</template>
<script>

import E from 'wangeditor'
let editor;

export default {
  data () {
    return {
      form:{},
      formTitle:'',
      onedialogTableVisible:false,
      meetId:0,
      signNameList:[],
      meetingFilesList:[],
      twodialogTableVisible: false,
      threedialogVisible:false,
      DoneList: [],
      NotDoneList: [],
      activeName: 'done',
      queryDone: {
        pageSize: 4,
        currentPage: 1,
        pass: 1
      },
      queryNotDone: {
        pageSize: 4,
        currentPage: 1,
        pass: 0
      },
      doneTotal: 0,
      notDoneTotal: 0,
      options: [{
        value: '1',
        label: '产品室'
         }, {
        value: '2',
        label: '场景室'
         }, {
        value: '3',
        label: '数据室'
          }, {
        value: '4',
        label: '渠道室'
          }, {
        value: '5',
        label: '基础软件室'
      }],
      value: '',
      fileName:'',
      manList:[],
      participateList:[],
      departmentPersonnelList:[],
      centerDialogVisible: false,
      addDialogVisible:false,
      applyId:0,
      total: 0,
      qrCodeImg:'',
      btnText:'上传文档',
      read:'',
      enabledUploadBtn:true,
      filesUploadUrl:'http://localhost:3300/files/upload',
      requestHeader: {
          Authorization: window.sessionStorage.getItem('token')
        }
    }
  },
  created () {
    this.getDoneList()
    this.getNotDoneList()
  },
  methods: {
    judgeFileExist(fileIsExist){
      console.log(fileIsExist)
      if(fileIsExist !== 1){
        return false
      }else {
        return true
      }
    },
    UploadSuccess(res) {
      console.log(res)
      this.$refs.upload.clearFiles(); //去掉文件列表
      if (res.code == 100) {
        //刷新时执行的函数
       //this.reload()
       this.getDoneList()
       return this.$message.success('文件上传成功！')
      }else if(res.code != 100){
       return this.$message.error('文件上传失败！')
      }
    },
    async getMeetingFilesList(appId) {
       this.onedialogTableVisible = true;
       const { data: res } = await this.$http.post(
        "/files/getFilesListApply", {applyId: appId});
      if (res.code !== 100) {
        return this.$message.error("获取会议文档列表失败！");
      }
      this.meetingFilesList = res.extend.result;
      console.log(res);
    },
    async getSignNameList(appId) {
       this.twodialogTableVisible = true;
       const { data: res } = await this.$http.post(
        "/sign/getSignNameList", {applyId: appId});
      if (res.code !== 100) {
        return this.$message.error("获取签到名单失败！");
      }
      this.signNameList = res.extend.result;
      console.log(res);
    },
    exportToExcel() {
      if(this.signNameList == 0){
        return this.$message.error("暂无数据！");
      }
      this.$confirm('确定下载列表文件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.excelData = this.signNameList // 导出的数据list。
        this.export2Excel()
      }).catch(() => {})
    },
    export2Excel () {
      var that = this
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/assets/js/Export2Excel.js')// js文件的位置
        const tHeader = ['签到人','签到时间','签到IP地址','签到设备']
        const filterVal = ['staffName','signTime','signIp','signBrowser'] // 导出的表头字段名，需要导出表格字段名
        const list = that.signNameList
        const data = that.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, '签到名单')// 导出的表格名称
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
     fixdata(data) { // 文件流转BinaryString
      var o = ''
      var l = 0
      var w = 10240
      for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
      o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
      return o
    },
   async getMeetingFileList(mId) {
       //this.dialogTableVisible = true;
       const { data: res } = await this.$http.post(
        "/files/getFilesList", {meetingId: mId});
      this.meetingFilesList = res.extend.result;
      console.log(res);
    },
    async fileDownLoad(fileName,meetingId) {
       var load_url = '/files/'+ meetingId + '/' + fileName;
       console.log('http://localhost:3300'+load_url);
       window.open('http://localhost:3300'+load_url);
    },
    async fileDelete(fileName,meetingId) {

            const confirmResult = await this.$confirm('确定删除该文件？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            // this.$http.post('/files/getMeetingId',{fileName}).then(doc => {
            //       this.meetId = doc.data.extend.result
            // })

            //console.log(this.meetId)
            const { data: res } = await this.$http.delete( '/files/delete', { data:{fileName,meetingId}})
             if (res.code != 100) {
                return this.$message.error('删除失败！')
             }
            this.$message.success('删除成功！')
            this.getMeetingFileList(meetingId)
            this.getDoneList()
        },
    async getDoneList () {
      const { data: res } = await this.$http.post('/meeting/historyApply', this.queryDone )
      if (res.code !== 100) {
        return this.$message.error('获取历史会议列表失败！')
      }
      this.DoneList = res.extend.result.records
      this.doneTotal = res.extend.result.total
      console.log(res)
    },
    async getNotDoneList () {
      const { data: res } = await this.$http.post('/meeting/historyApply', this.queryNotDone )
      if (res.code !== 100) {
        return this.$message.error('获取历史会议列表失败！')
      }
      this.NotDoneList = res.extend.result.records
      this.notDoneTotal = res.extend.result.total
    },
     addEditor(applyId) {
      this.threedialogVisible = true
      this.form={applyId}
      this.$nextTick(() => {
        // 关联弹窗里面的div，new一个 editor对象
        if (!editor) {
          editor = new E('#div1')
          editor.create()

        }
        this.formTitle = ''
        editor.txt.text('')
      })
    },
    async fileEdit(fileName,meetingId,applyId) {
      this.form={applyId}
      const { data: res } = await this.$http.post("/files/readContent",{fileName,meetingId,applyId:this.form})
         this.read = res.extend.result
         console.log(res)
      this.threedialogVisible = true

      this.$nextTick(() => {
        // 关联弹窗里面的div，new一个 editor对象
        if (!editor) {
          editor = new E('#div1')
          editor.create()
        }
        this.formTitle = fileName
        editor.txt.text(this.read)
      })

    },
    async save() {
        var editorContent = editor.txt.text()
        const { data: res } = await this.$http.post("/files/contentSave", {editorContent,applyId:this.form,formTitle:this.formTitle})
          console.log(res)
          if (res.code !== 100) {
            return this.$message.error('提交失败！')
          } else {
            this.threedialogVisible = false
            this.getDoneList()
            return this.$message.success('提交成功！')
          }
    },
    handleSizeChangeDone (newSize) {
      this.queryDone.pageSize = newSize
      this.getDoneList()
    },
    handleCurrentChangeDone (newPage) {
      this.queryDone.currentPage = newPage
      this.getDoneList()
    },
    handleSizeChangeNotDone (newSize) {
      this.queryNotDone.pageSize = newSize
      this.getNotDoneList()
    },
    handleCurrentChangeNotDone (newPage) {
      this.queryNotDone.currentPage = newPage
      this.getNotDoneList()
    },
    //查询相应部门对应的人员名单
    async selectDepartment(department){
      //找出value对应的label
      let obj = {};
      obj = this.options.find((item)=>{//这里的options就是上面遍历的数据源
        return item.value === department;//筛选出匹配数据
      });
      //请求
      const { data: res } = await this.$http.post('/apply/selectdepartment', { department: obj.label,applyId:this.applyId })
      if (res.code !== 100) {
        return this.$message.error('获取信息失败！')
      }else{
        this.departmentPersonnelList = res.extend.result
      }
    },
    //获取参会人员名单
    async handleAdd(Id) {
      this.applyId=Id;
      const { data: res } = await this.$http.post('/apply/queryparticipate',  { applyId: Id })
      if (res.code !== 100) {
        return this.$message.error('参会人员信息获取失败！')
      }else{
        this.participateList = res.extend.result
        this.addDialogVisible=true;
      }
    },
    //获取二维码
    async handleSign(id){
      const { data: res } = await this.$http.post('/sign/meetingId',  { applyId: id })
      if (res.code !== 100) {
        return this.$message.error('二维码获取失败')
      }else{
        this.qrCodeImg='http://127.0.0.1:3300/sign/createqrcode?id='+res.extend.result
        console.log(this.qrCodeImg)
        this.centerDialogVisible = true;
      }

    },
    //根据部门名单中的名字 向参与名单中添加名字
    addParticipate(staff){
      let obj = {};
      obj = this.participateList.find((item)=>{//这里的options就是上面遍历的数据源
        return item.staffId === staff.staffId;//筛选出匹配数据
      });
      if(obj===undefined){
        this.participateList.push(staff);
      }else{
        this.$message.error("此人已存在！！!")
      }

    },
    //删除参与名单中的名字
    removeParticipate(index){
      this.participateList.splice(index,1) ;
    },
    //提交修改后的参与名单
    async submitParticcipate(){
      let staffId=[];
      let i=0;
      this.participateList.forEach(element => {
        staffId[i]=element.staffId
        i++;
      });
      console.log(staffId)
      const { data: res } = await this.$http.post('/apply/changeparticipate',{staffId:staffId,applyId:this.applyId})
      if (res.code !== 100) {
        return this.$message.error('更新参会名单失败！')
      }else{
        return this.$message.success('更新参会名单成功')

      }
      this.addDialogVisible = false


    }

  }
}
</script>

<style scoped>
.el-tabs {
  margin-top: 15px;
}
.el-table{
  font-size: 13.5px
}
.outButton{
  position:absolute;
  right:45px;
  top:55px;
}
.inline-block {
  display: inline-block;
}
</style>
